package com.yjc.drygoods.order.interceptor;

import com.yjc.common.constant.AuthServerConstant;
import com.yjc.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;

/**
 * @author yjc
 * @create 2022-09-23 20:47
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        HashSet<String> set = new HashSet<>();
        set.add("/order/order/get/everyone/consumeTotal");
        set.add("/alipay/notify");
        set.add("/order/order/getOrderInfo");
        set.add("/order/order/list");
        set.add("/order/orderitem/list");
        set.add("/order/order/info");
        set.add("/order/order/save");
        set.add("/order/order/update");
        set.add("/order/order/getAllOrder/with/orderItems");
        boolean match = set.contains(requestURI);

        if (match) {
            return true;
        }

        MemberRespVo attribute = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            loginUser.set(attribute);
            return true;
        } else {
            session.setAttribute("msg", "请先登录");
            response.sendRedirect("http://auth.drygoods.top/login.html");
            return false;
        }
    }
}
